﻿using System;
using System.CodeDom.Compiler;
using Cfg.Exceptions;
using Cfg.ValidationAttributes;
using NUnit.Framework;

namespace Cfg.Test.Validators
{
    [TestFixture]
    public class MaxAttributeTest
    {
        public interface ITestConfig
        {
            [Max(1)]
            int ValueThatDoesNotExist { get; }
 
            [Max(-1)]
            int ValueThatDoesNotExistButHasNegativeMaxValue { get; }

            IMaxAttributeTestSection Max { get; }
        }

        public interface IMaxAttributeTestSection
        {
            [Max(5, "IntSmallerThanMaxValue")]
            int IntSmallerThanMaxValue { get; }

            [Max(5, "IntGreaterThanMaxValue")]
            int IntGreaterThanMaxValue { get; }

            [Max(5, "IntEqualToMaxValue")]
            int IntEqualToMaxValue { get; }
        }

        [Test]
        public void MaxNoContext()
        {
            try
            {
                AppSettings.Init<ITestConfig>();
            }
            catch (ConfigValidationException<ITestConfig> ex)
            {
                // value that does not exist and have negative max value should fail
                Assert.AreEqual(1, ex.ValidationErrors.Length);
            }

            // configuration should be still usable
            var cfg = AppSettings.Get<ITestConfig>();
            Assert.AreEqual(0, cfg.ValueThatDoesNotExist);
        }

        [Test]
        public void IntGreaterThanMaxValue()
        {
            try
            {
                AppSettings.Init<ITestConfig>("IntGreaterThanMaxValue");
            }
            catch (ConfigValidationException<ITestConfig> ex)
            {
                Console.WriteLine(ex);
            }
        }

        [Test]
        public void IntSmallerThanMaxValue()
        {
            try
            {
                AppSettings.Init<ITestConfig>("IntSmallerThanMaxValue");
            }
            catch
            {
                Assert.AreEqual(1, AppSettings.Get<ITestConfig>().Max.IntSmallerThanMaxValue);
            }
        }

        [Test]
        public void IntEqualToMaxValue()
        {
            ITestConfig cfg = null;
            try
            {
                AppSettings.Init<ITestConfig>("IntEqualToMaxValue");
                cfg = AppSettings.Get<ITestConfig>();
            }
            catch
            {
                Assert.AreEqual(5, AppSettings.Get<ITestConfig>().Max.IntEqualToMaxValue);                
            }
        }
    }
}